/**
 * 熵巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 数据查询模块
 * 尊重劳动成果是一种美德
 */

let currentQueryData = [];
let isQueryLoading = false;
let queryCurrentPage = 1;
let queryPageSize = 500;

// 截断文本函数
function truncateText(text, maxLength) {
    if (typeof text !== 'string') {
        text = String(text);
    }
    
    if (text.length <= maxLength) {
        return text;
    }
    
    return text.substring(0, maxLength) + '...';
}

// 页面加载后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 添加调试信息
    console.log('data-query.js 已加载');
    
    // 初始化日期输入框
    initializeDateInputs();
    
    // 监听TAB切换，切换到数据查询TAB时加载表单选择器
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                const target = mutation.target;
                if (target.id === 'data-query' && target.classList.contains('active')) {
                    loadQuerySchemaSelector();
                }
            }
        });
    });
    
    const dataQueryTab = document.getElementById('data-query');
    if (dataQueryTab) {
        observer.observe(dataQueryTab, { attributes: true });
        // 如果已经是激活状态，立即加载
        if (dataQueryTab.classList.contains('active')) {
            setTimeout(() => loadQuerySchemaSelector(), 500);
        }
    }
    
    // 取消自动查询，改为手动点击查询
    // 不再监听TAB切换事件进行自动查询
    
    // 添加全局图片加载监听器
    document.addEventListener('error', function(e) {
        if (e.target.tagName === 'IMG' && e.target.src.includes('image_proxy.php')) {
            console.error('图片加载失败:', e.target.src);
            console.error('图片ID:', e.target.src.split('id=')[1]);
        }
    }, true);
    
    // 添加全局鼠标移动监听器，确保预览窗口及时消失
    document.addEventListener('mousemove', function(e) {
        const preview = document.getElementById('image-preview');
        if (preview) {
            // 检查鼠标是否在图片上
            const hoveredElement = document.elementFromPoint(e.clientX, e.clientY);
            if (!hoveredElement || 
                (hoveredElement.tagName !== 'IMG' || 
                 !hoveredElement.src.includes('image_proxy.php'))) {
                hideImagePreview();
            }
        }
    });
});

// 加载表单选择器
function loadQuerySchemaSelector() {
    const select = document.getElementById('query-schema-select');
    if (!select) {
        console.error('数据查询表单选择器元素未找到');
        return;
    }
    
    console.log('开始加载数据查询表单选择器');
    
    fetch('api/get_schemas.php')
        .then(response => {
            if (!response.ok) {
                throw new Error('HTTP ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            if (data.success && data.schemas) {
                let html = '';
                data.schemas.forEach((schema, index) => {
                    const selected = index === 0 ? 'selected' : '';
                    html += `<option value="${schema.schema_key}" ${selected}>${schema.schema_name}</option>`;
                });
                if (data.schemas.length > 1) {
                    html += '<option value="all">全部表单</option>';
                }
                select.innerHTML = html;
                console.log('数据查询表单选择器加载成功，共', data.schemas.length, '个表单');
            } else {
                select.innerHTML = '<option value="default">默认表单</option>';
            }
        })
        .catch(error => {
            console.error('加载数据查询表单选择器失败:', error);
            select.innerHTML = '<option value="default">默认表单</option>';
        });
}

// 初始化日期输入框
function initializeDateInputs() {
    const today = new Date().toISOString().split('T')[0];
    const startDateInput = document.getElementById('query-start-date');
    const endDateInput = document.getElementById('query-end-date');
    
    if (startDateInput) startDateInput.value = today;
    if (endDateInput) endDateInput.value = today;
}

// 切换查询日期输入框显示
function toggleQueryDateInputs() {
    const dateType = document.getElementById('query-date-type').value;
    const customDates = document.getElementById('query-custom-dates');
    
    if (dateType === 'custom') {
        customDates.style.display = 'flex';
    } else {
        customDates.style.display = 'none';
    }
}

// 重置查询过滤条件
function resetQueryFilters() {
    document.getElementById('query-date-type').value = 'today';
    document.getElementById('query-data-limit').value = '5000';
    document.getElementById('query-sort-order').value = 'desc';
    initializeDateInputs();
    toggleQueryDateInputs();
    updateQueryStatus('请选择筛选条件，点击"查询数据"按钮开始查询...', '');
    
    // 清空查询结果
    const resultsDiv = document.getElementById('query-results');
    if (resultsDiv) {
        resultsDiv.innerHTML = '';
    }
}

// 获取查询过滤参数
function getQueryFilterParams() {
    const schemaSelect = document.getElementById('query-schema-select');
    const dateType = document.getElementById('query-date-type').value;
    const dataLimit = document.getElementById('query-data-limit').value;
    const sortOrder = document.getElementById('query-sort-order').value;
    
    let startDate, endDate;
    
    switch (dateType) {
        case 'today':
            startDate = new Date().toISOString().split('T')[0];
            endDate = startDate;
            break;
        case 'yesterday':
            const yesterday = new Date();
            yesterday.setDate(yesterday.getDate() - 1);
            startDate = yesterday.toISOString().split('T')[0];
            endDate = startDate;
            break;
        case 'week':
            const weekAgo = new Date();
            weekAgo.setDate(weekAgo.getDate() - 7);
            startDate = weekAgo.toISOString().split('T')[0];
            endDate = new Date().toISOString().split('T')[0];
            break;
        case 'month':
            const monthAgo = new Date();
            monthAgo.setMonth(monthAgo.getMonth() - 1);
            startDate = monthAgo.toISOString().split('T')[0];
            endDate = new Date().toISOString().split('T')[0];
            break;
        case 'custom':
            startDate = document.getElementById('query-start-date').value;
            endDate = document.getElementById('query-end-date').value;
            break;
    }
    
    return {
        schemaKey: schemaSelect ? schemaSelect.value : 'default',
        dateType: dateType,
        startDate: startDate,
        endDate: endDate,
        dataLimit: parseInt(dataLimit),
        sortOrder: sortOrder
    };
}

// 手动查询
function manualQuery() {
    const filters = getQueryFilterParams();
    console.log('手动查询:', filters);
    performQuery(filters);
}

// 执行查询
function performQuery(filters) {
    if (isQueryLoading) return;
    
    console.log('开始查询数据...', filters);
    updateQueryStatus(`正在查询数据 (${filters.startDate} 至 ${filters.endDate})...`, 'loading');
    isQueryLoading = true;
    
    // 构建请求参数
    const params = new URLSearchParams({
        action: 'query_data',
        schema_key: filters.schemaKey,
        date_type: filters.dateType,
        start_date: filters.startDate,
        end_date: filters.endDate,
        data_limit: filters.dataLimit,
        sort_order: filters.sortOrder
    });
    
    fetch(`api/data_query.php?${params.toString()}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => {
        console.log('HTTP状态:', response.status);
        console.log('Content-Type:', response.headers.get('content-type'));
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            console.warn('响应不是JSON格式:', contentType);
            throw new Error('服务器返回非 JSON 数据，可能出现错误');
        }
        
        return response.text();
    })
    .then(text => {
        console.log('原始响应:', text.substring(0, 200));
        
        // 检查是否是HTML错误页面
        if (text.trim().startsWith('<') || 
            text.includes('<html') || 
            text.includes('<br />') || 
            text.includes('<b>') ||
            text.includes('Fatal error') ||
            text.includes('Parse error')) {
            throw new Error('API返回HTML错误页面而非JSON数据，请检查服务器配置');
        }
        
        // 检查是否为空响应
        if (!text || text.trim() === '') {
            throw new Error('服务器返回空响应');
        }
        
        // 尝试解析JSON
        try {
            return JSON.parse(text);
        } catch (parseError) {
            console.error('JSON解析错误:', parseError.message);
            console.error('响应内容:', text);
            throw new Error(`JSON解析失败: ${parseError.message}，响应内容可能不是有效的JSON格式`);
        }
    })
    .then(data => {
        console.log('数据查询响应:', data);
        if (data.success) {
            currentQueryData = data.data;
            displayQueryResults(data.data, data.schema_code, data.total_count);
            const dateRange = filters.startDate === filters.endDate ? filters.startDate : `${filters.startDate} 至 ${filters.endDate}`;
            updateQueryStatus(`数据查询成功，共 ${data.total_count} 条数据 (${dateRange})`, 'success');
        } else {
            updateQueryStatus('查询失败: ' + data.message, 'error');
            console.error('数据查询失败:', data);
        }
    })
    .catch(error => {
        updateQueryStatus('查询异常: ' + error.message, 'error');
        console.error('数据查询异常:', error);
    })
    .finally(() => {
        isQueryLoading = false;
    });
}

// 显示查询结果
function displayQueryResults(data, schemaCode, totalCount) {
    const resultsList = document.getElementById('query-results');
    if (!resultsList) {
        console.error('找不到query-results元素');
        return;
    }
    
    console.log('开始显示查询结果:', { totalCount, dataLength: data.length });
    
    // 保存到全局变量
    currentQueryData = data;
    queryCurrentPage = 1;
    
    let html = '';
    
    if (data.length === 0) {
        html = '<div class="no-data">暂无数据</div>';
    } else {
        // 计算分页
        const totalPages = Math.ceil(data.length / queryPageSize);
        const startIndex = (queryCurrentPage - 1) * queryPageSize;
        const endIndex = Math.min(startIndex + queryPageSize, data.length);
        const pageData = data.slice(startIndex, endIndex);
        
        // 创建表格
        html = `
            <table class="data-table">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>图片</th>
                        <th>附件</th>
                        <th>ID</th>
                        <th>标题</th>
                        <th>创建</th>
                        <th>更多</th>
                    </tr>
                </thead>
                <tbody>
        `;
        
        pageData.forEach((item, index) => {
            const serialNumber = startIndex + index + 1;
            html += createTableRow(item, serialNumber);
        });
        
        html += `
                </tbody>
            </table>
        `;
        
        // 添加分页控件
        if (totalPages > 1) {
            html += createQueryPagination(totalPages, data.length);
        }
    }
    
    resultsList.innerHTML = html;
    console.log('查询结果显示完成');
}

// 创建表格行
function createTableRow(item, serialNumber) {
    // 获取所有图片字段的图片，在独立列中展示
    let imageGallery = '';
    if (item.image_fields && item.image_fields.length > 0) {
        const allImages = [];
        item.image_fields.forEach(imageField => {
            if (imageField.value) {
                const images = extractImageIds(imageField.value);
                allImages.push(...images);
            }
        });
        
        if (allImages.length > 0) {
            imageGallery = allImages.map((imageId, index) => {
                return `<img src="api/image_proxy.php?id=${imageId}" 
                            style="width:50px;height:50px;margin:2px;cursor:pointer;object-fit:cover;border:1px solid #ddd;border-radius:4px;" 
                            title="图片 ID: ${imageId.substring(0, 8)}" 
                            onmouseenter="showImagePreview(this, '${imageId}')" 
                            onmouseleave="hideImagePreview()" 
                            onclick="viewImage('${imageId}')" 
                            onerror="this.style.display='none';" 
                            onload="console.log('图片加载成功:', '${imageId.substring(0, 8)}')">`;
            }).join('');
        }
    }
    
    // 获取所有附件字段的附件，在独立列中展示
    let attachmentGallery = '';
    if (item.all_fields && Object.keys(item.all_fields).length > 0) {
        const allAttachments = [];
        for (const fieldCode in item.all_fields) {
            const field = item.all_fields[fieldCode];
            if (field.is_attachment && field.raw_value) {
                const attachments = extractAttachmentIds(field.raw_value);
                allAttachments.push(...attachments);
            }
        }
        
        if (allAttachments.length > 0) {
            attachmentGallery = allAttachments.map(attachmentId => {
                const fileIcon = getFileIcon(attachmentId);
                const fileType = getFileType(attachmentId);
                // 使用流水号+标题作为文件名
                const seqNo = item.seq_no || '';
                const title = item.title || '';
                const fileName = seqNo ? `${seqNo}_${title}` : title || 'attachment';
                return `<div class="attachment-preview" 
                           style="display:inline-block;margin:2px;padding:6px;background:#f8f9fa;border:1px solid #ddd;border-radius:4px;text-align:center;cursor:pointer;min-width:60px;" 
                           title="${fileType} - 点击下载" 
                           onclick="downloadAttachment('${attachmentId}', '${fileName.replace(/'/g, "\\'")}')">
                           <div style="font-size:16px;margin-bottom:2px;">${fileIcon}</div>
                           <div style="font-size:10px;color:#666;">${fileType}</div>
                           <div style="font-size:9px;color:#999;">${attachmentId.substring(0, 6)}</div>
                         </div>`;
            }).join('');
        }
    }
    
    let fieldsHtml = '';
    
    if (item.all_fields && Object.keys(item.all_fields).length > 0) {
        const fieldId = 'fields_' + item.id.replace(/-/g, '_');
        fieldsHtml = `
            <div>
                <button onclick="toggleFields('${fieldId}')" style="background:none;border:1px solid #ccc;padding:5px 10px;cursor:pointer;">展开</button>
                <div id="${fieldId}" style="display:none;margin-top:10px;">
                    <table class="field-table">
        `;
        
        for (const fieldCode in item.all_fields) {
            const field = item.all_fields[fieldCode];
            let valueHtml = '';
            
            if (field.is_image && field.raw_value) {
                // 图片字段只显示地址文本，不显示图片
                valueHtml = field.display_value;
            } else if (field.is_attachment && field.raw_value) {
                // 附件字段只显示地址文本，不显示下载链接
                valueHtml = field.display_value;
            } else {
                valueHtml = field.display_value;
            }
            
            fieldsHtml += `
                <tr>
                    <td>${field.field_name}</td>
                    <td>${valueHtml}</td>
                </tr>
            `;
        }
        
        fieldsHtml += `
                    </table>
                </div>
            </div>
        `;
    }
    
    return `
        <tr>
            <td style="text-align:center;">${serialNumber}</td>
            <td style="text-align:center;">${imageGallery || '无图片'}</td>
            <td style="text-align:center;">${attachmentGallery || '无附件'}</td>
            <td>${item.id.substring(0, 8)}</td>
            <td>${truncateText(item.title, 30)}</td>
            <td>${formatDateTime(item.created_time)}</td>
            <td>${fieldsHtml}</td>
        </tr>
    `;
}

// 切换字段显示
function toggleFields(fieldId) {
    const element = document.getElementById(fieldId);
    const button = element.previousElementSibling;
    if (element.style.display === 'none') {
        element.style.display = 'block';
        button.textContent = '折叠';
    } else {
        element.style.display = 'none';
        button.textContent = '展开';
    }
}

// 创建数据项HTML
function createDataItem(item) {
    let html = `
        <div class="data-item">
            <div class="data-header">
                <h3 class="data-title">${truncateText(item.title, 40)}</h3>
                <div class="data-meta">
                    <span class="data-id">ID: ${item.id}</span>
                    <span class="data-time">创建: ${formatDateTime(item.created_time)}</span>
                </div>
            </div>
    `;
    
    // 显示所有业务字段数据
    if (item.all_fields && Object.keys(item.all_fields).length > 0) {
        html += '<div class="data-fields">';
        
        // 按字段类型分组显示
        const imageFields = [];
        const attachmentFields = [];
        const normalFields = [];
        
        for (const fieldCode in item.all_fields) {
            const field = item.all_fields[fieldCode];
            if (field.is_image) {
                imageFields.push({ code: fieldCode, ...field });
            } else if (field.is_attachment) {
                attachmentFields.push({ code: fieldCode, ...field });
            } else {
                normalFields.push({ code: fieldCode, ...field });
            }
        }
        
        // 先显示图片字段
        imageFields.forEach(field => {
            html += createFieldDisplay(field, true);
        });
        
        // 再显示附件字段 - 必须在图片字段之后
        attachmentFields.forEach(field => {
            html += createFieldDisplay(field, false, true);
        });
        
        // 最后显示普通字段
        normalFields.forEach(field => {
            html += createFieldDisplay(field);
        });
        
        html += '</div>';
    }
    
    html += '</div>';
    
    return html;
}

// 创建字段显示HTML
function createFieldDisplay(field, isImage = false, isAttachment = false) {
    let html = `
        <div class="field-display ${isImage ? 'image-field' : ''} ${isAttachment ? 'attachment-field' : ''}">
            <div class="field-label">
                <span class="field-name">${field.field_name}</span>
                <span class="field-code">(${field.code})</span>
            </div>
            <div class="field-value">
    `;
    
    if (isImage && field.raw_value) {
        // 图片字段显示
        const images = extractImageIds(field.raw_value);
        if (images.length > 0) {
            html += '<div class="image-gallery">';
            images.forEach(imageId => {
                html += `
                    <div class="image-item">
                        <img src="api/image_proxy.php?id=${imageId}" 
                             alt="${field.field_name}" 
                             style="max-width:200px;max-height:200px;object-fit:contain;border:1px solid #ddd;cursor:pointer;border-radius:4px;"
                             title="图片 ID: ${imageId.substring(0, 8)}"
                             loading="lazy"
                             onmouseenter="showImagePreview(this, '${imageId}')" 
                             onmouseleave="hideImagePreview()" 
                             onclick="viewImage('${imageId}')"
                             onerror="this.style.display='none';" 
                             onload="console.log('字段图片加载成功:', '${imageId.substring(0, 8)}')">
                    </div>
                `;
            });
            html += '</div>';
        } else {
            html += `<span class="field-text">${field.display_value}</span>`;
        }
    } else if (isAttachment && field.raw_value) {
        // 附件字段显示
        const attachments = extractAttachmentIds(field.raw_value);
        if (attachments.length > 0) {
            html += '<div class="attachment-list">';
            attachments.forEach(attachmentId => {
                const fileIcon = getFileIcon(attachmentId);
                const fileType = getFileType(attachmentId);
                // 使用字段名作为文件名
                const fileName = field.field_name || 'attachment';
                html += `
                    <div class="attachment-item" style="display:inline-block;margin:5px;">
                        <div class="attachment-card" 
                             style="padding:10px;border:1px solid #ddd;border-radius:6px;background:#f8f9fa;text-align:center;cursor:pointer;min-width:80px;transition:all 0.2s ease;" 
                             title="${fileType} - 点击下载" 
                             onclick="downloadAttachment('${attachmentId}', '${fileName.replace(/'/g, "\\'")}')">
                            <div style="font-size:24px;margin-bottom:5px;">${fileIcon}</div>
                            <div style="font-size:12px;color:#333;font-weight:bold;">${fileType}</div>
                            <div style="font-size:10px;color:#666;margin-top:3px;">${attachmentId.substring(0, 8)}</div>
                        </div>
                    </div>
                `;
            });
            html += '</div>';
        } else {
            html += `<span class="field-text">${field.display_value}</span>`;
        }
    } else {
        // 普通字段显示
        html += `<span class="field-text">${field.display_value}</span>`;
    }
    
    html += `
            </div>
        </div>
    `;
    
    return html;
}

// 提取图片ID
function extractImageIds(value) {
    const ids = [];
    
    if (!value) return ids;
    
    if (typeof value === 'string') {
        // 先检查是否直接是一个UUID
        if (isValidUuid(value.trim())) {
            ids.push(value.trim());
        } else {
            try {
                // 尝试解析JSON数组
                const decoded = JSON.parse(value);
                if (Array.isArray(decoded)) {
                    decoded.forEach(item => {
                        if (typeof item === 'string' && isValidUuid(item)) {
                            ids.push(item);
                        } else if (typeof item === 'object' && item.id && isValidUuid(item.id)) {
                            ids.push(item.id);
                        } else if (typeof item === 'object' && item.refId && isValidUuid(item.refId)) {
                            ids.push(item.refId);
                        }
                    });
                }
            } catch (e) {
                // JSON解析失败，尝试其他方式
                console.warn('图片ID解析失败:', value);
            }
        }
    } else if (Array.isArray(value)) {
        // 直接是数组格式
        value.forEach(item => {
            if (typeof item === 'string' && isValidUuid(item)) {
                ids.push(item);
            } else if (typeof item === 'object' && item.id && isValidUuid(item.id)) {
                ids.push(item.id);
            } else if (typeof item === 'object' && item.refId && isValidUuid(item.refId)) {
                ids.push(item.refId);
            }
        });
    }
    
    return ids;
}

// 提取附件ID
function extractAttachmentIds(value) {
    return extractImageIds(value); // 附件和图片的提取逻辑相同
}

// 验证UUID格式
function isValidUuid(uuid) {
    const uuidRegex = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
    return uuidRegex.test(uuid);
}

// 测试图片代理服务
function testImageProxy(imageId) {
    console.log('正在测试图片代理服务:', imageId);
    
    fetch(`api/image_proxy.php?id=${imageId}`)
        .then(response => {
            console.log('图片代理服务响应:', {
                status: response.status,
                statusText: response.statusText,
                contentType: response.headers.get('content-type'),
                url: response.url
            });
            
            if (!response.ok) {
                return response.text().then(text => {
                    throw new Error(`HTTP ${response.status}: ${text}`);
                });
            }
            return response.blob();
        })
        .then(blob => {
            console.log('图片数据:', {
                size: blob.size,
                type: blob.type
            });
            
            if (blob.size === 0) {
                console.error('图片数据为空');
            }
        })
        .catch(error => {
            console.error('图片代理服务错误:', error);
        });
}

// 显示图片悬停预览
function showImagePreview(element, imageId) {
    // 移除已存在的预览
    hideImagePreview();
    
    const preview = document.createElement('div');
    preview.id = 'image-preview';
    preview.style.cssText = `
        position: fixed;
        z-index: 10000;
        background: rgba(0,0,0,0.9);
        border: 2px solid #fff;
        border-radius: 8px;
        box-shadow: 0 8px 16px rgba(0,0,0,0.3);
        padding: 5px;
        pointer-events: none;
        transition: opacity 0.2s ease;
        opacity: 0;
    `;
    
    const img = document.createElement('img');
    img.src = `api/image_proxy.php?id=${imageId}`;
    img.style.cssText = `
        max-width: 300px;
        max-height: 300px;
        object-fit: contain;
        border-radius: 4px;
    `;
    
    preview.appendChild(img);
    document.body.appendChild(preview);
    
    // 定位预览窗口
    const rect = element.getBoundingClientRect();
    const previewWidth = 310; // 预估宽度
    const previewHeight = 310; // 预估高度
    
    let left = rect.right + 10;
    let top = rect.top;
    
    // 确保不超出屏幕边界
    if (left + previewWidth > window.innerWidth) {
        left = rect.left - previewWidth - 10;
    }
    if (top + previewHeight > window.innerHeight) {
        top = window.innerHeight - previewHeight - 10;
    }
    if (left < 0) left = 10;
    if (top < 0) top = 10;
    
    preview.style.left = left + 'px';
    preview.style.top = top + 'px';
    
    // 淡入效果
    setTimeout(() => {
        if (preview.parentNode) {
            preview.style.opacity = '1';
        }
    }, 10);
    
    // 图片加载失败处理
    img.onerror = function() {
        if (preview.parentNode) {
            preview.innerHTML = '<div style="color:white;padding:20px;text-align:center;">图片加载失败</div>';
        }
    };
}

// 隐藏图片悬停预览
function hideImagePreview() {
    const preview = document.getElementById('image-preview');
    if (preview) {
        preview.style.opacity = '0';
        setTimeout(() => {
            if (preview.parentNode) {
                document.body.removeChild(preview);
            }
        }, 100); // 缩短延时，快速移除
    }
}
// 查看图片大图
function viewImage(imageId) {
    const imageUrl = `api/image_proxy.php?id=${imageId}`;
    
    // 创建模态窗口显示大图
    const modal = document.createElement('div');
    modal.className = 'image-modal';
    modal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.8);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 10000;
        cursor: pointer;
        opacity: 0;
        transition: opacity 0.3s ease;
    `;
    
    const img = document.createElement('img');
    img.src = imageUrl;
    img.style.cssText = `
        max-width: 90%;
        max-height: 90%;
        object-fit: contain;
        border: 2px solid white;
        border-radius: 4px;
        box-shadow: 0 8px 16px rgba(0,0,0,0.5);
        transform: scale(0.8);
        transition: transform 0.3s ease;
    `;
    
    // 图片加载完成后的动画
    img.onload = function() {
        modal.style.opacity = '1';
        img.style.transform = 'scale(1)';
    };
    
    // 图片加载失败处理
    img.onerror = function() {
        modal.innerHTML = '<div style="color:white;text-align:center;"><h3>图片加载失败</h3><p>点击关闭</p></div>';
        modal.style.opacity = '1';
    };
    
    modal.appendChild(img);
    document.body.appendChild(modal);
    
    // 点击关闭
    modal.onclick = function() {
        modal.style.opacity = '0';
        setTimeout(() => {
            if (modal.parentNode) {
                document.body.removeChild(modal);
            }
        }, 300);
    };
    
    // ESC键关闭
    const escListener = function(e) {
        if (e.key === 'Escape') {
            modal.style.opacity = '0';
            setTimeout(() => {
                if (modal.parentNode) {
                    document.body.removeChild(modal);
                }
            }, 300);
            document.removeEventListener('keydown', escListener);
        }
    };
    document.addEventListener('keydown', escListener);
}

// 格式化日期时间
function formatDateTime(dateString) {
    if (!dateString) return '';
    
    try {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    } catch (e) {
        return dateString;
    }
}

// 更新查询状态显示
function updateQueryStatus(message, type) {
    const statusElement = document.getElementById('query-status');
    if (statusElement) {
        statusElement.textContent = message;
        statusElement.className = 'query-status ' + type;
        console.log('状态更新:', message, type);
    }
}

// 根据文件ID或扩展名获取文件图标
function getFileIcon(attachmentId, filename = '') {
    // 如果有文件名，优先使用文件名判断
    const fileExt = filename ? filename.split('.').pop().toLowerCase() : '';
    
    // 文档类型
    if (['pdf'].includes(fileExt)) return '📄';
    if (['doc', 'docx'].includes(fileExt)) return '📝';
    if (['xls', 'xlsx'].includes(fileExt)) return '📊';
    if (['ppt', 'pptx'].includes(fileExt)) return '📋';
    if (['txt'].includes(fileExt)) return '📃';
    
    // 图像类型
    if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(fileExt)) return '🖼️';
    
    // 压缩文件
    if (['zip', 'rar', '7z', 'tar', 'gz'].includes(fileExt)) return '🗜️';
    
    // 视频文件
    if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'].includes(fileExt)) return '🎬';
    
    // 音频文件
    if (['mp3', 'wav', 'flac', 'aac', 'ogg'].includes(fileExt)) return '🎵';
    
    // 默认文件图标
    return '📎';
}

// 根据文件ID或扩展名获取文件类型描述
function getFileType(attachmentId, filename = '') {
    const fileExt = filename ? filename.split('.').pop().toLowerCase() : '';
    
    const typeMap = {
        'pdf': 'PDF',
        'doc': 'Word', 'docx': 'Word',
        'xls': 'Excel', 'xlsx': 'Excel',
        'ppt': 'PPT', 'pptx': 'PPT',
        'txt': '文本',
        'jpg': '图片', 'jpeg': '图片', 'png': '图片', 'gif': '图片', 'bmp': '图片', 'webp': '图片',
        'zip': '压缩包', 'rar': '压缩包', '7z': '压缩包', 'tar': '压缩包', 'gz': '压缩包',
        'mp4': '视频', 'avi': '视频', 'mov': '视频', 'wmv': '视频', 'flv': '视频', 'mkv': '视频',
        'mp3': '音频', 'wav': '音频', 'flac': '音频', 'aac': '音频', 'ogg': '音频'
    };
    
    return typeMap[fileExt] || '文件';
}

// 下载附件
function downloadAttachment(attachmentId, customName = '') {
    // 创建隐藏的下载链接
    const link = document.createElement('a');
    
    // 如果提供了自定义文件名，添加到URL参数中
    if (customName) {
        link.href = `api/attachment_proxy.php?id=${attachmentId}&name=${encodeURIComponent(customName)}`;
    } else {
        link.href = `api/attachment_proxy.php?id=${attachmentId}`;
    }
    
    link.download = '';
    link.target = '_blank';
    
    // 添加到页面并触发点击
    document.body.appendChild(link);
    link.click();
    
    // 清理
    setTimeout(() => {
        document.body.removeChild(link);
    }, 100);
    
    // 显示下载提示
    showDownloadNotification(customName || attachmentId);
}

// 显示下载通知
function showDownloadNotification(fileName) {
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #4CAF50;
        color: white;
        padding: 10px 20px;
        border-radius: 4px;
        z-index: 10001;
        font-size: 14px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        opacity: 0;
        transition: opacity 0.3s ease;
    `;
    
    // 显示文件名或ID的前8位
    const displayName = fileName.length > 30 ? fileName.substring(0, 30) + '...' : fileName;
    notification.textContent = `正在下载: ${displayName}`;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.style.opacity = '1';
    }, 10);
    
    // 3秒后消失
    setTimeout(() => {
        notification.style.opacity = '0';
        setTimeout(() => {
            if (notification.parentNode) {
                document.body.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

// 创建分页控件
function createQueryPagination(totalPages, totalRecords) {
    let html = '<div style="text-align:center;margin-top:20px;padding:15px;">';
    
    html += `<span style="margin-right:15px;color:#666;">共 ${totalRecords} 条数据，共 ${totalPages} 页</span>`;
    
    // 首页
    if (queryCurrentPage > 1) {
        html += `<a href="javascript:void(0)" onclick="goToQueryPage(1)" style="margin:0 5px;color:#007bff;text-decoration:none;">首页</a>`;
        html += `<a href="javascript:void(0)" onclick="goToQueryPage(${queryCurrentPage - 1})" style="margin:0 5px;color:#007bff;text-decoration:none;">上一页</a>`;
    }
    
    // 页码
    let startPage = Math.max(1, queryCurrentPage - 2);
    let endPage = Math.min(totalPages, queryCurrentPage + 2);
    
    for (let i = startPage; i <= endPage; i++) {
        if (i === queryCurrentPage) {
            html += `<span style="margin:0 5px;padding:5px 10px;background:#007bff;color:white;border-radius:3px;">${i}</span>`;
        } else {
            html += `<a href="javascript:void(0)" onclick="goToQueryPage(${i})" style="margin:0 5px;padding:5px 10px;color:#007bff;text-decoration:none;">${i}</a>`;
        }
    }
    
    // 尾页
    if (queryCurrentPage < totalPages) {
        html += `<a href="javascript:void(0)" onclick="goToQueryPage(${queryCurrentPage + 1})" style="margin:0 5px;color:#007bff;text-decoration:none;">下一页</a>`;
        html += `<a href="javascript:void(0)" onclick="goToQueryPage(${totalPages})" style="margin:0 5px;color:#007bff;text-decoration:none;">尾页</a>`;
    }
    
    html += '</div>';
    return html;
}

// 跳转到指定页码
function goToQueryPage(page) {
    queryCurrentPage = page;
    
    const resultsList = document.getElementById('query-results');
    if (!resultsList || !currentQueryData || currentQueryData.length === 0) {
        return;
    }
    
    const totalPages = Math.ceil(currentQueryData.length / queryPageSize);
    const startIndex = (queryCurrentPage - 1) * queryPageSize;
    const endIndex = Math.min(startIndex + queryPageSize, currentQueryData.length);
    const pageData = currentQueryData.slice(startIndex, endIndex);
    
    let html = `
        <table class="data-table">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>图片</th>
                    <th>附件</th>
                    <th>ID</th>
                    <th>标题</th>
                    <th>创建</th>
                    <th>更多</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    pageData.forEach((item, index) => {
        const serialNumber = startIndex + index + 1;
        html += createTableRow(item, serialNumber);
    });
    
    html += `
            </tbody>
        </table>
    `;
    
    // 添加分页控件
    if (totalPages > 1) {
        html += createQueryPagination(totalPages, currentQueryData.length);
    }
    
    resultsList.innerHTML = html;
    
    // 滚动到顶部
    resultsList.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
